package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.AddReservationDto;
import com.zzyl.nursing.dto.TimeSlotCountDto;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.ReservationVo;
import com.zzyl.nursing.vo.TimeCountVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Override
    public Integer cancelledCount() {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        //获取当前线程的id
        Long userId = UserThreadLocal.getUserId();
        String userID = String.valueOf(userId);
        Integer count = reservationMapper.cancelledCount(userID, startTime, endTime);
        return count;
    }

    @Override
    public List<TimeCountVo> countReservationsForTime(Long time) {
        // 时间戳转 LocalDateTime（毫秒级时间戳）
        LocalDateTime startTime = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 计算 30 分钟后
        LocalDateTime endTime = startTime.plusMinutes(30);
        List<TimeCountVo> timeCountVos = reservationMapper.countReservationsForTime(startTime, endTime);

        return timeCountVos.stream()
                .filter(vo -> vo.getCount() != 6)
                .collect(Collectors.toList());
    }

    @Override
    public Integer add(ReservationVo reservationVo) {
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getTime, reservationVo.getTime());
        Long count = reservationMapper.selectCount(queryWrapper);
        if (count >= 6) {
            throw new RuntimeException("当前时间段预约数量已经超过6个");
        }

        Reservation reservation = new Reservation();
        reservation.setCreateTime(new java.util.Date());
        reservation.setUpdateTime(new java.util.Date());
        //调用ThreadLocal获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        String userID = String.valueOf(userId);
        reservation.setCreateBy(userID);
        reservation.setUpdateBy(userID);
        reservation.setName(reservationVo.getName());
        reservation.setMobile(reservationVo.getMobile());
        String time = reservationVo.getTime();
// 将字符串时间转换为LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        reservation.setTime(localDateTime);
        reservation.setType(reservationVo.getType());
        reservation.setVisitor(reservationVo.getVisitor());

        //新增校验
        //当前时间段预约数量是否超过六个'


        return reservationMapper.insert(reservation);
    }


    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    @Override
    public void setstatus(Long id) {
        Long userId = UserThreadLocal.getUserId();
        String userID = String.valueOf(userId);
        LocalDateTime updateTime = LocalDateTime.now();
        reservationMapper.setstatus(id,updateTime, userID);



    }

    /**
     * 查询当天取消预约数量（按当前用户）
     * @return
     */

    @Override
    public int getTodayCancelledCountByUser() {
        LocalDate today = LocalDate.now();
        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = today.atTime(23, 59, 59);
        //获取用户ID
        Long userId = UserThreadLocal.getUserId();


        //获取取消预约数量

        int i = reservationMapper.countTodayCancelledByUser(userId, startTime, endTime);
        return i;
    }

    /**
     * 新增预约
     * @param dto
     * @return
     */
    @Override
    public boolean addReservation(AddReservationDto dto) {
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        //调用ThreadLocal获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        String userID = String.valueOf(userId);
        dto.setCreateBy(userID);
        dto.setUpdateBy(userID);

        //新增校验
        //当前时间段预约数量是否超过六个'
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getTime, dto.getTime());
        Long count = reservationMapper.selectCount(queryWrapper);
        if (count >= 6) {
            return false;
        }
        //校验当前用户取消取消预约数量是否大于3
        if (getTodayCancelledCountByUser() >= 3) {
            return false;
        }

        return reservationMapper.insertReservation(dto) > 0;
    }


    @Override
    public void updateReservationStatus() {
        LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Reservation::getStatus, 0);
        queryWrapper.le(Reservation::getTime, LocalDateTime.now());
        List<Reservation> list = list(queryWrapper);
        for (Reservation reservation : list) {
            reservation.setStatus(3);
        }
        updateBatchById(list);
    }


    // 查询指定日期各时间段剩余预约次数
    @Override
    public List<TimeSlotCountDto> getTimeSlotCounts(Long timeMillis) {
        LocalDateTime inputLdt = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(timeMillis),
                ZoneId.systemDefault()
        );
        LocalDate targetDate = inputLdt.toLocalDate();
        LocalDateTime startOfDay = targetDate.atStartOfDay();
        LocalDateTime endOfDay = targetDate.atTime(23, 59, 59);
        return reservationMapper.selectTimeSlotCounts(startOfDay, endOfDay);
    }
    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return getById(id);
    }


    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        return save(reservation)?1:0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return updateById(reservation)?1:0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return removeById(id)?1:0;
    }


}
